package dao.jpa;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;

public class DAOJPA {
	
	private static EntityManagerFactory emf = null;
	private static EntityManager em = null;
	private static EntityTransaction tx = null;
	
	public static EntityManager getManager() {
		if (em == null) {
			emf = Persistence.createEntityManagerFactory("gestion_films");
			em = emf.createEntityManager();
			tx = em.getTransaction();
		}
		
		if (!tx.isActive()) {
			tx.begin();
		}
		
		return em;
	}

	public static void commit() {
		/* Pour la fonction Remove
		 * Article aToRemove=em.merge(a);
		 * em.remove(aToRemove);
		 * 
		 * 
		 */
	 	em.flush();
	 	em.clear();
	 	tx.commit();
	}
	public static void rollback() {
	 	tx.rollback();
	}
	public static void close() {
	 	em.close(); em = null;
	 	emf.close();emf = null;
	}
	
	public static void viderBase() {
		getManager().createQuery("DELETE FROM Personne").executeUpdate();
		getManager().createNativeQuery("ALTER TABLE personne AUTO_INCREMENT = 1").executeUpdate();
//		getManager().createQuery("DELETE FROM Article").executeUpdate();
//		getManager().createNativeQuery("ALTER TABLE article AUTO_INCREMENT = 1").executeUpdate();
//		getManager().createQuery("DELETE FROM Page").executeUpdate();
//		getManager().createNativeQuery("ALTER TABLE page AUTO_INCREMENT = 1").executeUpdate();			
		}
}
